const Product  = require('../models/product');
const Cart = require('../models/cart');


exports.getProducts = (req, res, next)=>{
    const products = Product.fetchAll(products=>   res.render('shop/product-list', {
        prods: products,
        pageTitle:'所有产品',
        path: '/products'
    }));
 
}
exports.getIndex= (req, res, next)=>{
    const products = Product.fetchAll(products=>   res.render('shop/index', {
        prods: products,
        pageTitle:'商店',
        path: '/'
    }));
 
}

exports.getProductsId = (req, res, next)=>{
    const proId = req.params.productId;
    Product.findById(proId, product =>{ 
        res.render('shop/product-detail', {
        product: product,
        pageTitle: product.title,
        path:'/products'
    })
   });

}

exports.getCart = (req, res, next) => {
    Cart.getCart(cart=>{
        Product.fetchAll(products =>{
            const cartProducts = [];
            for(product of products){
                const cartProductData = cart.products.find(prod => prod.id === product.id);
                if(cartProductData){
                    cartProducts.push({productData: product, quantity: cartProductData.quantity})
                }
            }
            res.render('shop/cart',{
                path:'/cart',
                pageTitle:'我的购物车',
                products:cartProducts
            })
        })
    })
   
}
exports.getToCart = (req, res, next)=>{
  const proId = req.body.productId;
  Product.findById(proId, product=>{
      Cart.addProduct(proId, product.price);
  })
  res.redirect('/cart')
}

exports.getOrders = (req, res, next) => {
    res.render('shop/orders',{
        path:'/orders',
        pageTitle:'结算页面'
    })
} 

exports.getCheckout = (req, res, next) => {
    res.render('shop/checkout',{
        path:'/checkout',
        pageTitle:'结算页面'
    })
}
 
exports.postCartDeleteProduct =(req, res, next)=>{
    const prodId = req.body.productId;
    Product.findById(prodId, product =>{
        console.log(product);
        Cart.deleteProduct(prodId, product.price);
        res.redirect('/cart')
    })
}


